﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosionDamage : MonoBehaviour
{
    public float destorySlefTime = 2f;//自毁时间
    public float explosionRadius = 5.0f;//爆炸影响半径
    public float explosionDamage = 500f;//爆炸中心的破坏力
    public float explosionPower = 1000f;//爆炸产生的爆炸力
    private void Awake()
    {
        //延时销毁
        Destroy(gameObject,destorySlefTime);
    }

    private void Start()
    {
        //爆炸中心位置
        Vector3 explosionPosition = transform.position;
        //返回爆炸中心球形半径(包括半径)内所有的碰撞体，放到数组中
        Collider[] hitColliders = Physics.OverlapSphere(explosionPosition, explosionRadius);
        //计算爆炸伤害
        for(int i =0;i< hitColliders.Length; i++)
        {
            //计算从爆炸中心到碰撞体表面的距离
            //返回碰撞体与爆炸中心最近的点
            Vector3 closestPoint = hitColliders[i].ClosestPointOnBounds(explosionPosition);
            //计算距离
            float distance = Vector3.Distance(closestPoint,explosionPosition);
            //计算伤害点数的百分比，随着距离的增大降低(Clamp01 钳制数值在0~1之间  )
            float hitPointPercentage = 1.0f - Mathf.Clamp01(distance / explosionRadius);
            //计算最后总的伤害点数
            float damage = hitPointPercentage * explosionDamage;
            //向受到影响的碰撞体发送伤害消息，调用该物体的减血方法
            hitColliders[i].SendMessageUpwards("TakeDamage",damage,SendMessageOptions.DontRequireReceiver);
            //如果碰撞体上有刚体组件，则施加一个爆炸力
            if(hitColliders[i].GetComponent<Rigidbody>() != null)
            {
                hitColliders[i].GetComponent<Rigidbody>().
                    AddExplosionForce(explosionPower,//力度
                                      explosionPosition,//爆炸中心位置
                                      explosionRadius);//爆炸影响半径
            }

        }

    }

}